﻿using System;
using System.Web;
using System.Web.Security;
using INHollandair.Core.Enum;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/Default.aspx");
            }
            if(!IsIpBlocked())
            {
                pnl_Login.Visible = true;
                pnl_BlockedIp.Visible = false;
                UserName.Focus();
                pnl_Login.DefaultButton = "LoginButton";
            }

            int maxAttempts = (Session["attempts"] == null) ? 5 : 5 - ((int)Session["attempts"]);
            AttemptsLabel.Text = String.Format("Inlog pogingen over: {0}.", maxAttempts.ToString());
        }

        protected void LoginClick(object sender, EventArgs e)
        {
            string user = Server.HtmlEncode(UserName.Text);
            string pass = Server.HtmlEncode(Password.Text);
            bool rememberMe = chk_remember.Checked;

            if (user.Length > 0 && pass.Length > 0)
            {
                UserService svc = new UserService();
                string salt = svc.GetUserSaltByName(user);
                string hash = salt == null? String.Empty : EncryptionUtils.Hash(pass, salt);

                LoginEnum login = svc.Login(user, hash);
                switch (login)
                {
                    case LoginEnum.NotFound:
                        errorLabel.Text = "Naam of wachtwoord incorrect.";
                        Session["attempts"] = (Session["attempts"] == null) ? 1 : ((int)Session["attempts"]) + 1;
                        break;
                    case LoginEnum.NotActivated:
                        errorLabel.Text = "Account is nog niet geactiveerd.";
                        break;
                    case LoginEnum.Succes:
                        Session["attempts"] = 5;
                        FormsAuthentication.RedirectFromLoginPage(user, rememberMe);
                        break;
                }
            }

            int maxAttempts = (Session["attempts"] == null) ? 5 : 5 - ((int)Session["attempts"]);
            AttemptsLabel.Text = String.Format("Inlog pogingen over: {0}.", maxAttempts.ToString());
        }

        public bool IsIpBlocked()
        {
            int maxAttempts = (Session["attempts"] == null) ? 0 : ((int)Session["attempts"]);
            BlockedIpService svc = new BlockedIpService();
            BlockedIp blockedIp = svc.GetBlockedIpByIp(Request.UserHostAddress);
            if (blockedIp != null)
            {
                if (blockedIp.Created.AddMinutes(5) >= DateTime.Now)
                {
                    blockedIp.Created = DateTime.Now;
                    svc.UpdateBlockedIp(blockedIp);
                    ChangePanels(blockedIp);
                    return true;
                }
                svc.RemoveBlockedIp(blockedIp);
            }
            else if (maxAttempts >= 4)
            {
                blockedIp = new BlockedIp
                {
                    Ip = Request.UserHostAddress,
                    Created = DateTime.Now
                };
                svc.InsertBlockedIp(blockedIp);
                ChangePanels(blockedIp);
                LogEvent();
                return true;
            }
            return false;
        }

        public void ChangePanels(BlockedIp blockedIp)
        {
            pnl_Login.Visible = false;
            pnl_BlockedIp.Visible = true;
            BlockedLabel.Text = string.Format(
                    "Wegens een overvloed aan requests van uw IP is uw IP voor 5 minuten geblokkeerd. U kunt gedurende deze tijd niet inloggen. De IP blocker is ingegaan op {0}.",
                    blockedIp.Created.ToShortTimeString());
        }

        private void LogEvent()
        {
            string ip = Request.UserHostAddress;

            EventLogService svc = new EventLogService();
            EventLog eventToLog = new EventLog
            {
                Description = string.Format("IP: {0} || Message: Login attempt limit exceeded..", ip),
                DateLogged = DateTime.Now
            };
            svc.InsertEventLog(eventToLog);
        }
    }
}
